import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/Utils/storage'
import router from '@/router'
import { Message } from 'element-ui'
const state = {
  token: getToken() ? JSON.parse(getToken()).token : '',
  userName: getToken() ? JSON.parse(getToken()).userName : '',
  userId: getToken() ? JSON.parse(getToken()).userId : ''
}
const mutations = {
  updateToken (state, data) {
    state.token = data.token
    state.userName = data.userName
    state.userId = data.userId
    setToken(JSON.stringify(data))
  },
  delToken (state) {
    removeToken()
    state.token = null
    state.userName = null
    state.userId = null
  }
}
const actions = {
  async asyncLogin (context, data) {
    const res = await login(data)
    // console.log(res)
    if (!res.data.regionId) {
      return Message.error(res.data.msg)
    }
    context.commit('updateToken', res.data)
    router.push('/index')
  },
  // 删除token
  delToken (context) {
    context.commit('delToken')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
